package servlet;

import com.alibaba.fastjson.JSON;
import mapper.UserMapper;
import pojo.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@WebServlet(name = "UserServlet", value = "/user")
public class UserServlet extends HttpServlet {

    UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        switch (method){
            case "checkUsername":
                checkUsername(request,response);
                break;
            case "registerUser":
                registerUser(request,response);
                break;
        }

    }

    private void registerUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        boolean b = userService.register(username, password);

        HashMap<String, String> map = new HashMap<>();
        if(b){
            //REGISTER_SUCCESS注册成功
            map.put("result","REGISTER_SUCCESS");
        }else {
            map.put("result","REGISTER_FAIL");
        }
        String r = JSON.toJSONString(map);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.write(r);
    }


    private void checkUsername(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        boolean b = userService.checkUsername(username);

        HashMap<String, String> map = new HashMap<>();
        if(b){
            map.put("result","USERNAME_EXIST");
        }else {
            map.put("result","USERNAME_CAN_USE");
        }
        String r = JSON.toJSONString(map);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.write(r);



    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
